import { getLineUpMessage } from "../../api";
import WKSDK from "wukongimjssdk";
import KOCSIM from "../../initKOCSIM";

let lineUpTimer: any = null;
// 容错次数
let errorCountLimit = 5;
let errorCount = 0;
// 查询次数
let lineUpCount = 0;
let islineUpMsgViewCreated = false;

// 排队监听
export default {
  init: async () => {
    // 单次监听视图组件是否加载完成
    uni.$once("line-up-mounte", (mounted: boolean) => {
      islineUpMsgViewCreated = mounted;
    });

    // 立即更新一次
    updateLineUpMsg();
    // 设置定时器
    if (lineUpTimer) {
      clearInterval(lineUpTimer);
    }
    // 每10秒更新一次
    lineUpTimer = setInterval(async () => {
      try {
        await updateLineUpMsg();
      } catch (error) {
        errorCount++;
        if (errorCount >= errorCountLimit) {
          clearInterval(lineUpTimer);
          lineUpTimer = null;
          return;
        }
        console.error(error);
      }
    }, 10000);

    async function updateLineUpMsg() {
      lineUpCount++;
      const pam = { channelId: KOCSIM.inst().currentChannel.channelID, uid: WKSDK.shared().config.uid };
      const { data: lineUpRes } = await getLineUpMessage(pam);
      console.log(" ☄ 排队监听中", lineUpRes);
      if (lineUpRes.waitCount <= 0) {
        uni.$emit("sendLocalMsg", {
          type: "ordinary",
          content: "很高兴为您服务",
          from: "system",
          time: new Date().getTime(),
        });
        // 清除排队监听
        clearInterval(lineUpTimer);
        lineUpTimer = null;
        lineUpCount = 0;
        return;
      }
      if (!islineUpMsgViewCreated) {
        // 发送 排队信息到聊天列表
        uni.$emit("sendLocalMsg", {
          type: "lineup",
          content: lineUpRes.waitCount,
          from: "system",
          time: new Date().getTime(),
        });
        //  addMessage({
        //   type: "lineup",
        //   content: lineUpRes.waitCount,
        //   from: "system",
        //   time: new Date().getTime(),
        // });
        // lineUpMsgContext = messageList[lineUpMsgIndex];
      } else {
        // lineUpMsgContext.content = lineUpRes.waitCount;
        uni.$emit("updateLineUpCount", lineUpRes.waitCount);
      }
    }
  },
  destroy: () => {
    if (lineUpTimer) {
      clearInterval(lineUpTimer);
      lineUpTimer = null;
      lineUpCount = 0;
    }
  }
};
